package org.aksw.xoperator.transform;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SimpleXslTransformer implements ITransformSparqlToText {
	{
		System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
	}

	private Log log = LogFactory.getLog(SimpleXslTransformer.class);

	public SimpleXslTransformer() {
		try {
			this.trans = TransformerFactory.newInstance().newTransformer(new StreamSource(this.getClass().getResourceAsStream("/transformation.xsl")));
		} catch (TransformerConfigurationException e) {
			log.error(e);
		} catch (TransformerFactoryConfigurationError e) {
			log.error(e);
		}
	}

	private Transformer trans;

	/* (non-Javadoc)
	 * @see org.aksw.xoperator.transform.ITransformSparqlToText#transformXML(java.lang.String)
	 */
	public String transformXML(String input) {
		Source xml = new StreamSource(new StringReader(input));
		StringWriter text = new StringWriter();
		synchronized (this.trans) {
			try {
				this.trans.transform(xml, new StreamResult(text));
			} catch (TransformerException e) {
				String err = "Unable to transform the result";
				this.log.error(err, e);
				text.append(err);
			}
		}

		return text.toString();
	}

}
